/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dto.HistoryBid;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import pojo.ChiTietMuaNgay;
import pojo.Chitietdaugia;
import pojo.Daugiathanhcong;
import pojo.Sanpham;
import pojo.Sanphamyeuthich;
import pojo.Taikhoan;
import util.HibernateUtil;
import util.UtilCommon;

/**
 *
 * @author WMThiet
 */
public class AjaxDAO {
    
    public static HistoryBid GetNewBid(long giaHienTai, int masp){
        Session session = HibernateUtil.getSessionFactory().openSession();
        HistoryBid historyBid = null;
        try{
            
            String hql = "from Chitietdaugia ct where ct.sanpham.maSanPham =:masp and ct.giaDau >:gia";
            Query query= session.createQuery(hql);
            query.setInteger("masp", masp);
            query.setLong("gia", giaHienTai);
            List<Chitietdaugia> listCT = query.list();
            Chitietdaugia ct = null;
            
            if(listCT != null){
                ct = listCT.get(listCT.size() - 1);
                historyBid = new HistoryBid();
                historyBid.setBidId(ct.getMaChiTietdaugia());
                historyBid.setTimeBid(UtilCommon.DateToString(ct.getThoiGiandaugia()));
                historyBid.setUserBid(ct.getTaikhoan().getTenTaiKhoan());
                historyBid.setValueBid(UtilCommon.customFormat("###,###", ct.getGiaDau()));
                historyBid.setPriceCurrent(ct.getGiaDau());
                long plus = ct.getGiaDau() - ct.getSanpham().getGiaKhoiDiem();
                historyBid.setValuePlus(UtilCommon.customFormat("###,###", plus));
            }
            
        }catch(Exception ex){
            historyBid = null;
        }finally{
            session.close();
        }
        
        return historyBid;
    }
    
    public static List<HistoryBid> GetHistoryList(int id,int maxResult){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Chitietdaugia> listDauGia = null;
        List<HistoryBid> historyBid = new ArrayList<HistoryBid>();
        
        try {
            session.beginTransaction();
            String hql = "from Chitietdaugia ct where ct.sanpham.maSanPham=:masp order by ct.giaDau desc";
            Query query = session.createQuery(hql);
            query.setInteger("masp",id);
            
            if(maxResult != -1){
                query.setMaxResults(maxResult);
            }
            
            listDauGia = query.list();
            
            if(listDauGia.isEmpty() == false){
                for (Chitietdaugia ct : listDauGia) {
                    HistoryBid hb = new HistoryBid();
                    hb.setBidId(ct.getMaChiTietdaugia());
                    hb.setTimeBid(UtilCommon.DateToString(ct.getThoiGiandaugia()));
                    hb.setUserBid(ct.getTaikhoan().getTenTaiKhoan());
                    hb.setValueBid(UtilCommon.customFormat("###,###", ct.getGiaDau()));
                    long plus = ct.getGiaDau() - ct.getSanpham().getGiaKhoiDiem();
                    hb.setValuePlus(UtilCommon.customFormat("###,###", plus));
                    historyBid.add(hb);
                }
            }
            
        } catch (Exception ex) {
            historyBid = null;
        } finally {
            session.close();
        }

        return historyBid;
    }
    
    public static Sanphamyeuthich LayYeuThich(int masp, int matk){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Sanphamyeuthich spyeuthich = null;
        try{
            session.beginTransaction();
            String hql = "from Sanphamyeuthich spyt where spyt.taikhoan.maTaiKhoan =:matk and spyt.sanpham.maSanPham =:masp";
            Query query = session.createQuery(hql);
            query.setInteger("matk", matk);
            query.setInteger("masp", masp);
            
            spyeuthich = (Sanphamyeuthich)query.uniqueResult();
        
        }catch(Exception e){
            spyeuthich = null;
        }
        finally{
            session.close();
        }
        
        return spyeuthich;
    }
    
    
    public static boolean AddFavor(int maSP,int maTK){
        Session session = HibernateUtil.getSessionFactory().openSession();
        boolean bDone = false;
        try{
            session.beginTransaction();
            
            Sanphamyeuthich spyeuthich = LayYeuThich(maSP, maTK);
            
            if(spyeuthich != null){
                if(spyeuthich.getDaHuy() == true){
                    
                    Sanphamyeuthich sanphamyeuthich = (Sanphamyeuthich)session.get(Sanphamyeuthich.class, spyeuthich.getMaYeuThich());
                    sanphamyeuthich.setDaHuy(false);
                    
                    session.update(sanphamyeuthich);
                    session.getTransaction().commit();  
                }
            } else{
                Sanpham sp = (Sanpham)session.get(Sanpham.class, maSP);
                Taikhoan tk = (Taikhoan)session.get(Taikhoan.class, maTK);

                if(sp == null || tk == null){
                    return false;
                }

                Sanphamyeuthich spyt = new Sanphamyeuthich();
                spyt.setSanpham(sp);
                spyt.setTaikhoan(tk);
                spyt.setDaHuy(false);

                session.save(spyt);
                session.getTransaction().commit();  
            }           
                      
            bDone = true;
            
        }catch(Exception ex){
            session.getTransaction().rollback();
            bDone = false;
        }finally{
            session.close();
        }
        
        return bDone;
    }   
    
    public static boolean RemoveFavor(int masp,int matk){
        Session session = HibernateUtil.getSessionFactory().openSession();
        boolean bDone = false;
        try{
            session.beginTransaction();
            
            Sanphamyeuthich spyeuthich = LayYeuThich(masp, matk);
            
            if(spyeuthich != null){
                Sanphamyeuthich sanphamyeuthich = (Sanphamyeuthich)session.get(Sanphamyeuthich.class, spyeuthich.getMaYeuThich());
                sanphamyeuthich.setDaHuy(true);
                
                session.update(sanphamyeuthich);
                session.getTransaction().commit(); 
            }                         
            
            bDone = true;
            
        }catch(Exception ex){
            session.getTransaction().rollback();
            bDone = false;
        }finally{
            session.close();
        }
        
        return bDone;
    }
    
    public static boolean CheckFavor(int maSP,int maTK){
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            session.beginTransaction();            
            
            Sanphamyeuthich spyeuthich = LayYeuThich(maSP, maTK);
            if(spyeuthich == null || spyeuthich.getDaHuy() == true){
                return false;
            }
            
            return true;
        
        }finally{
            session.close();
        }
    }
    
    public static int TinhSoLuotDauGia(int masp){
        List<HistoryBid> listHistoryBid = GetHistoryList(masp, -1);
        
        if(listHistoryBid == null)
            return 0;
        
        return listHistoryBid.size();
    }
    
    public static List<String> LayTinTucCapNhat(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<String> listNews = new ArrayList<String>();
        
        try{
            session.beginTransaction();            
            
            //Lấy từ bản đấu giá thành công:
            Daugiathanhcong daugiaTC = DauGiaThanhCongDAO.LaySPDauGiaThanhCongGanNhat();
            if(daugiaTC != null){
                String tenTK = daugiaTC.getTaikhoan().getTenTaiKhoan();
                String tenSP = daugiaTC.getChitietdaugia().getSanpham().getTenSanPham();
                String giaDau = UtilCommon.customFormat("#,###", daugiaTC.getGiaKhopLenh()) + " VNĐ";
                String message = String.format("<strong>%s</strong> đã dành chiến thắng trong phiên đấu giá sản phẩm <strong>%s</strong> với giá đấu <strong>%s</strong>",tenTK,tenSP,giaDau);
                listNews.add(message);
            }
            
            //Lấy từ lịch sử mua ngay:
            ChiTietMuaNgay ctMuaNgay = ChiTietMuaNgayDAO.LayChiTietMuaNgayGanNhat();
            if(ctMuaNgay != null){
                String tk = ctMuaNgay.getTaiKhoan().getTenTaiKhoan();
                String sp = ctMuaNgay.getSanPham().getTenSanPham();
                String giaMuaNgay = UtilCommon.customFormat("#,###", ctMuaNgay.getSanPham().getGiaMuaNgay()) + " VNĐ";
                String message = String.format("<strong>%s</strong> đã MUA NGAY sản phẩm <strong>%s</strong> với giá <strong>%s</strong>",tk,sp,giaMuaNgay);
                listNews.add(message);
            }
            
            //Lấy từ thông tin Chi tiết đấu giá:
             Chitietdaugia ctDauGia = ChiTietDauGiaDAO.LayChiTietDauGiaGanNhat();
            if(ctDauGia != null){
                String tk = ctDauGia.getTaikhoan().getTenTaiKhoan();
                String sp = ctDauGia.getSanpham().getTenSanPham();
                String giaDau = UtilCommon.customFormat("#,###", ctDauGia.getSanpham().getGiaHienTai()) + " VNĐ";
                String message = String.format("<strong>%s</strong> vừa đặt giá sản phẩm <strong>%s</strong> -> <strong>%s</strong>",tk,sp,giaDau);
                listNews.add(message);
            }
            
        }catch(Exception ex){            
        }finally{
            session.close();
        }
        
        return listNews;
    }
}
